﻿using System.Collections.ObjectModel;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using TxtManager.Application.DTOs;
using TxtManager.Application.Services;

namespace TxtManager.WPF.ViewModels;

public partial class MainWindowViewModel : ObservableObject
{
    private const int PageSize = 15;

    private readonly TextService _textService;

    [ObservableProperty]
    private ObservableCollection<TextItemDto> _items = new();

    [ObservableProperty]
    private TextItemDto? _selectedItem;

    [ObservableProperty]
    private string _searchKeyword = string.Empty;

    [ObservableProperty]
    private int _currentPage = 1;

    [ObservableProperty]
    private int _totalPages = 1;

    [ObservableProperty]
    private bool _isCreateItemPopupOpen = false;

    [ObservableProperty]
    private CreateItemDialogViewModel _createItemViewModel = new();

    public bool CanGoToPreviousPage => CurrentPage > 1;
    public bool CanGoToNextPage => CurrentPage < TotalPages;

    public MainWindowViewModel(TextService textService)
    {
        _textService = textService;
        LoadItemsCommand.ExecuteAsync(null);
        
        // 监听搜索关键字变化，自动触发搜索
        PropertyChanged += (s, e) => 
        {
            if (e.PropertyName == nameof(SearchKeyword))
            {
                CurrentPage = 1; // 重置到第一页
                LoadItemsCommand.ExecuteAsync(null);
            }
        };
    }

    [RelayCommand]
    private async Task LoadItemsAsync()
    {
        try
        {
            var result = await _textService.SearchItemAsync(
                CurrentPage,
                PageSize,
                SearchKeyword);

            Items = new ObservableCollection<TextItemDto>(result.Items);
            TotalPages = result.TotalPages;
            
            // 通知属性变化以更新分页按钮状态
            OnPropertyChanged(nameof(CanGoToPreviousPage));
            OnPropertyChanged(nameof(CanGoToNextPage));
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "加载失败", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    [RelayCommand]
    private async Task SaveItemAsync()
    {
        if (SelectedItem == null) return;

        try
        {
            await _textService.UpdateItemAsync(SelectedItem);
            MessageBox.Show("保存成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "保存失败", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    [RelayCommand]
    private async Task DeleteItemAsync()
    {
        if (SelectedItem == null) return;

        MessageBoxResult result = MessageBox.Show(
            $"确定要删除 [{SelectedItem.Title}] 吗？",
            "确认删除",
            MessageBoxButton.YesNo,
            MessageBoxImage.Question);

        if (result == MessageBoxResult.Yes)
        {
            try
            {
                await _textService.DeleteItemAsync(SelectedItem.Id);
                SelectedItem = null;
                await LoadItemsAsync();
                MessageBox.Show("删除成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "删除失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }

    [RelayCommand]
    private void CreateNewItem()
    {
        // 重置创建项的ViewModel
        CreateItemViewModel = new CreateItemDialogViewModel();
        IsCreateItemPopupOpen = true;
    }

    [RelayCommand]
    private async Task ConfirmCreateItemAsync()
    {
        var newItem = new TextItemDto
        {
            Title = CreateItemViewModel.Title,
            TextDescription = CreateItemViewModel.TextDescription,
            Tag = CreateItemViewModel.Tag
        };

        try
        {
            await _textService.CreateItemAsync(newItem);
            IsCreateItemPopupOpen = false;
            await LoadItemsAsync();
            
            // 选中新创建的项
            var createdItem = Items.FirstOrDefault(i => i.Title == newItem.Title);
            if (createdItem != null)
            {
                SelectedItem = createdItem;
            }
            
            MessageBox.Show("创建成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "创建失败", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    [RelayCommand]
    private void CancelCreateItem()
    {
        IsCreateItemPopupOpen = false;
    }

    [RelayCommand]
    private async Task NextPageAsync()
    {
        if (CurrentPage < TotalPages)
        {
            CurrentPage++;
            await LoadItemsAsync();
        }
    }

    [RelayCommand]
    private async Task PreviousPageAsync()
    {
        if (CurrentPage > 1)
        {
            CurrentPage--;
            await LoadItemsAsync();
        }
    }
}